package netty.nio.netty;

import netty.nio.netty.decoder.NettyDecoder;
import netty.nio.netty.decoder.TransportDecoder;
import netty.nio.netty.encoder.NettyEncoder;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

@Component
public class NettyClient implements Client {

    private ClientBootstrap bootstrap;
    private Channel channel;
    private String host;
    private int port;

    public NettyClient() throws InterruptedException {

        host = "127.0.0.1";
        port = 2525;

        if (bootstrap == null) {
            this.init();
            this.connect();

            //TODO Надо сделать, чтоб канал отключался после отправки всех сообщений
//            Thread.sleep(10000);

//            this.disconnect();
        }
    }

    @Override
    public void init() {
        //Создаем фабрику каналов. Так надо
        ChannelFactory channelFactory = new NioClientSocketChannelFactory(
                Executors.newCachedThreadPool(),
                Executors.newCachedThreadPool());

        bootstrap = new ClientBootstrap(channelFactory);

        //Создаем ChannelPipelineFactory
        bootstrap.setPipelineFactory(
                new ChannelPipelineFactory() {
                    @Override
                    public ChannelPipeline getPipeline() throws Exception {
                        return Channels.pipeline(
                                new NettyDecoder(new TransportDecoder()),
                                new NettyEncoder(),
                                new NettyHandler()
                        );
                    }
                }
        );
    }

    @Override
    public void connect() {
        channel = bootstrap.connect(new InetSocketAddress(host, port)).awaitUninterruptibly().getChannel();
        if(channel.isConnected()) {
            System.out.println("Netty Server: Connected to " +  host +", "+ port);
        }
        else {
            System.out.println("Netty Server: Can not cconnect to " + host +", "+ port);
        }
    }

    @Override
    public void disconnect() {
        if(channel.isConnected()) {
            channel.disconnect();
            System.out.println("Netty Server: Disconnected");
        }
        else {
            System.out.println("Netty Server: Nothing to disconnect");
        }
        bootstrap.releaseExternalResources();
    }
}
